from fastapi import APIRouter, Query, HTTPException
from starlette.responses import JSONResponse
import os
import shutil
from typing import Optional

# 使用统一的日志配置
from logging_config import get_logger

# 创建企业操作的路由
corp_router = APIRouter()

# 获取模块logger
logger = get_logger('corp_operations')

# 导入数据库连接函数和配置
import utils
from utils import nas_sqlite_dirdb_get, CONFIG,create_mysql_fileinfo_table
nas_create_corp_v1 = utils.nas_create_corp_v1
nas_add_folder_create_v1 = utils.nas_add_folder_create_v1
nas_rename_folder = utils.nas_rename_folder
query_mysql = utils.query_mysql
exec_mysql = utils.exec_mysql
execute_mysql_batch = utils.execute_mysql_batch
nas_delete = utils.nas_delete

# 企业相关接口

def get_corpid(corpid):   
    # 优先使用传入的大于0的corpid（如果数据库中不存在）
    if corpid and corpid.isdigit() and int(corpid) > 0:
        exists = query_mysql("SELECT COUNT(*) FROM corps WHERE corpid = %s", (corpid,))
        if exists and exists[0] == 0:
            return corpid
    # 如果不使用传入的corpid，则使用现有逻辑生成新的corpid
    max_corpid = query_mysql("SELECT MAX(corpid) FROM corps")
    if max_corpid is None or (max_corpid[0] is None) or int(max_corpid[0]) < 2000:
        return "2000"
    else:
        return str(int(max_corpid[0]) + 1)


@corp_router.get("/v1/oss/corp")
async def corp_management(
    action: str = Query(...),
    corpname: Optional[str] = Query(None),
    password: Optional[str] = Query(None),
    corpid: Optional[str] = Query(None),
    subid: Optional[str] = Query(None),
    uid: Optional[str] = Query(None),
    nickname: Optional[str] = Query(None),
    oldname: Optional[str] = Query(None)
):
    if action == "create":       
        if not corpname or not uid or not subid:
            return JSONResponse(content={"code": 400, "msg": "缺少必要参数: corpname, uid, subid"})
        exists = query_mysql("SELECT * FROM corps WHERE corpname = %s AND inuse=1", (corpname,), fetchone=True)
        if exists:
            return JSONResponse(content={"code": 400, "msg": "企业名称已存在"})           
        try:            
            corpid = get_corpid(corpid) 
            if nas_create_corp_v1(corpid, uid) != 0:                
                return JSONResponse(content={"code": 500, "msg": "企业目录创建失败"}) 
            sql_commands = [
                "INSERT INTO corps (corpid, corpname) VALUES (%s, %s)",
                "INSERT INTO employees (corpid, uid, subid, nickname, passwd) VALUES (%s, %s, %s, %s, %s)"
            ]
            params_list = [
                (corpid, corpname),
                (corpid, uid, subid, nickname, password or "")
            ]            
            if not execute_mysql_batch(sql_commands, params_list):
                return JSONResponse(content={"code": 500, "msg": "数据库操作失败"})
            create_mysql_fileinfo_table(corpid)    
            return JSONResponse(content={"code": 200})
        except Exception as e:            
            logger.error(f"企业注册失败: {e}")
            return JSONResponse(content={"code": 500, "msg": "内部错误"})
    
    elif action == "addsubid":
        # 添加员工
        if not corpid or not uid or not subid or not nickname:
            return JSONResponse(content={"code": 400, "msg": "缺少必要参数"})    
        exists = query_mysql("SELECT * FROM employees WHERE corpid = %s AND uid = %s AND subid = %s AND inuse=1", (corpid, uid, subid), fetchone=True)
        if exists:
            return JSONResponse(content={"code": 400, "msg": "员工已存在"})     
        try:
            # 先创建目录 sqllite
            if nas_add_folder_create_v1(str(corpid), "/", nickname, 1, uid, 0) != 0:
                return JSONResponse(content={"code": 500, "msg": "用户目录创建失败"}) 
            # 插入员工数据
            if not exec_mysql("INSERT INTO employees (corpid, uid, subid, nickname) VALUES (%s, %s, %s, %s)",(corpid, uid, subid, nickname)):
                return JSONResponse(content={"code": 500, "msg": "数据库操作失败"})
                
            return JSONResponse(content={"code": 200})
        except Exception as e:
            logger.error(f"添加员工失败: {e}")
            return JSONResponse(content={"code": 500, "msg": "内部错误"})
    
    elif action == "rename":       
        if not corpid or not uid or not subid or not nickname:
            return JSONResponse(content={"code": 400, "msg": "缺少必要参数"}) 
         # 检查员工是否存在
        result = query_mysql("SELECT nickname FROM employees WHERE corpid = %s AND uid = %s AND inuse=1 limit 1", (corpid, uid))
        if result:
            oldname = result[0]          
        else:
            return JSONResponse(content={"code": 400, "msg": "员工不存在"})
        # 更新sqllite            
        ret = nas_rename_folder(corpid, "/", oldname, nickname, 1,uid)
        if ret != 0:
            return JSONResponse(content={"code": 500, "msg": "私有根目录重命名失败"})      
        
        # 更新MySQL中的员工昵称
        if not exec_mysql("UPDATE employees SET nickname = %s WHERE corpid = %s AND uid = %s AND subid = %s",
                      (nickname, corpid, uid, subid)):
            return JSONResponse(content={"code": 500, "msg": "数据库操作失败"})                
        return JSONResponse(content={"code": 200})
    
    elif action == "delsubid":
        # 删除员工
        if not corpid or not uid or not subid:
            return JSONResponse(content={"code": 400, "msg": "缺少必要参数"})        
        # 从MySQL查询员工昵称
        result = query_mysql("SELECT nickname FROM employees WHERE corpid = %s AND uid = %s AND inuse=1 limit 1", (corpid, uid))
        if result:
            nickname = result[0]
        else:
            return JSONResponse(content={"code": 400, "msg": "员工不存在"})        
        # 删除sqllite目录
        ret = nas_delete(corpid,"", nickname, 0)
        if ret != 0:
            return JSONResponse(content={"code": 500, "msg": "私有根目录删除失败"})
        if not exec_mysql("UPDATE employees SET inuse = 0 WHERE corpid = %s AND uid = %s", (corpid, uid)):
            return JSONResponse(content={"code": 500, "msg": "MySQL数据库操作失败"})            
        return JSONResponse(content={"code": 200})
        
     
    elif action == "delcorp":
        # 删除企业 - 暂时为空，直接返回成功
        return JSONResponse(content={"code": 200})
    
    elif action == "getspace":
        # 查询企业存储空间
        if not corpid:
            return JSONResponse(content={"code": 400, "msg": "缺少必要参数"})        
        try:
            # 计算企业目录大小
            corp_dir = os.path.join(CONFIG["root_dir"], corpid)
            total_size = 0
            if os.path.exists(corp_dir):
                for dirpath, dirnames, filenames in os.walk(corp_dir):
                    for f in filenames:
                        fp = os.path.join(dirpath, f)
                        if os.path.exists(fp):
                            total_size += os.path.getsize(fp)
            
            return JSONResponse(content={"code": 200, "totalsize": str(total_size)})
        except Exception as e:
            print(f"查询存储空间失败: {e}")
            return JSONResponse(content={"code": 500, "msg": "内部错误"})
    
    else:
        return JSONResponse(content={"code": 400, "msg": "无效的操作类型"})